String Funtion and Method
Function :
A function is a block of code to carry out a specific task, will contain its own scope and is called by name. All functions may contain zero(no) arguments or more than one arguments. On exit, a function can or can not return one or more values.
- Function is block of code that is also called by its name. (independent)
- The function can have different parameters or may not have any at all. If any data (parameters) are passed, they are passed explicitly.
- It may or may not return any data.
- Function does not deal with Class and its instance concept.
def functionName( arg1, arg2,….):
…….
# Function_body
……..
Method
A method in python is somewhat similar to a function, except it is associated with object/classes. Methods in python are very similar to functions except for two major differences.
- Method is called by its name, but it is associated to an object (dependent).
- A method is implicitly passed the object on which it is invoked.
- It may or may not return any data.
- A method can operate on the data (instance variables) that is contained by the corresponding class
class ClassName:
def method_name():
…………..
# Method_body
………………
Built-in String Methods
Python includes the following built-in methods to manipulate strings −
- capitalize() - Capitalizes first letter of string.
Example -
s="apkZube"
print(s.capitalize()) #Apkzube
output of above example :
Apkzube
- count() - The count() method returns the number of occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation.
Syntax :
str.count(sub, start = 0,end = len(string))
- sub − This is the substring to be searched.
- start − Search starts from this index. First character starts from 0 index. By default search starts from 0 index.
- end − Search ends from this index. First character starts from 0 index. By default search ends at the last index.
s="I Love Python Tutorial"
print(s.count('o')) #3
print(s.count('o',5)) #2
print(s.count('t')) #2
print(s.count('t',2,9)) #0
output of above example :
3
2
2
0
- index() - The index() method determines if the string str occurs in string or in a substring of string, if the starting index beg and ending index end are given. This method is same as find(), but raises an exception if sub is not found.
syntax : str.index(str, beg ,end )
- str − This specifies the string to be searched.
- beg − This is the starting index, by default its 0.
- end − This is the ending index, by default its equal to the length of the string.
s="I Love Python Tutorial"
print(s.index('i'))
print(s.index('i',2))
print(s.index('Love'))
print(s.index('Love',7))
print(s.index('i',0,10))
output of above example :
19
0
19
2
Traceback (most recent call last):
File "main.py", line 16, in
print(s.index('Love',7)
ValueError: substring not found
- find() - The find() method determines if the string str occurs in string, or in a substring of string if the starting index beg and ending index end are given.
str.find(str, beg, end)
- str − This specifies the string to be searched.
- beg − This is the starting index, by default its 0.
- end − This is the ending index, by default its equal to the lenght of the string.
s="I Love Python Tutorial"
print(s.find('I'))
print(s.find('I',2))
print(s.find('Love'))
print(s.find('t',2,10))
output of above example :
0
-1
2
9
- isalpha() - The isalpha() method checks whether the string consists of alphabetic characters only.
syntax - str.isalpha()
s="I Love Python 3 Tutorial"
print(s.isalpha())
s="Python" # No space & digit in this string
print(s.isalpha())
output of above example :
False
True
- isalnum() - The isalnum() method checks whether the string consists of alphanumeric characters.
str.isalnum()
s="I Love Python 3 Tutorial"
print(s.isalnum())
s="Python" # No space
print(s.isalnum())
output of above example :
False
True
- isdigit() - The method isdigit() checks whether the string consists of digits only.
s="I Love Python 3 Tutorial"
print(s.isdigit())
s="123" # Only digit in this string
print(s.isdigit())
output of above example :
False
True
- islower() - The islower() method checks whether all the case-based characters (letters) of the string are lowercase.
example :
s="I Love Python 3 Tutorial"
print(s.islower())
p="python"
print(p.islower())
output of above example :
False
True
- isnumeric() - The isnumeric() method checks whether the string consists of only numeric characters. This method is present only on unicode objects.
Note − Unlike Python 2, all strings are represented in Unicode in Python 3. Given below is an example illustrating it.
Example :
str = "apkzube97"
print (str.isnumeric())
str = "10121997"
print (str.isnumeric())
output of above example :
False
True
- isspace() - The isspace() method checks whether the string consists of whitespace
Example :
str = " "
print (str.isspace())
str = "apkzube"
print (str.isspace())
output of above example :
True
False
- istitle() - The istitle() method checks whether all the case-based characters in the string following non-casebased letters are uppercase and all other case-based characters are lowercase.
Explanation:
s1='I Love Python Tutorial'
print(s1.istitle())
s2='I love python 3'
print(s2.istitle())
output of above example :
True
False
- len() - The len() method returns the length of the string.
Example -
s1='I Love Python Tutorial'
print(len(s1))
s2='I love python 3'
print(len(s2))
output of above example :
22
15
- lower() - The method lower() returns a copy of the string in which all case-based characters have been lowercased.
Example -
s1='I Love Python Tutorial'
print(s1.lower())
s2='I love python 3'
print(s2.lower())
output of above example :
i love python tutorial
i love python 3
- upper() - The upper() method returns a copy of the string in which all case-based characters have been uppercased
Example -
s1='I Love Python Tutorial'
print(s1.upper())
s2='I love python 3'
print(s2.upper())
output of above example :
I LOVE PYTHON TUTORIAL
I LOVE PYTHON 3
- max() - The max() method returns the max alphabetical character from the string str.
s1='I Love Python Tutorial'
print(max(s1))
s2='apkzube'
print(max(s2))
output of above example :
y
z
- min() - The min() method returns the min alphabetical character from the string str.
Example -
s1='PythonTutorial'
print(min(s1))
s2='apkzube'
print(min(s2))
output of above example :
P
a
- lstrip() - The lstrip() method returns a copy of the string in which all chars have been stripped from the beginning of the string (default whitespace characters).
- rstrip() - The rstrip() method returns a copy of the string in which all chars have been stripped from the end of the string (default whitespace characters).
str.lstrip([chars])
str.rstrip([chars])
Example -
s1=' I Love Python Tutorial '
print(s1.lstrip())
s2='###ApkZube###'
print(s2.lstrip('#'))
output of above example :
I Love Python Tutorial
ApkZube###
###ApkZube
- replace - The replace() method returns a copy of the string in which the occurrences of old have been replaced with new, optionally restricting the number of replacements to max.
str.replace(old, new,[max])
Exmple -
- old − This is old substring to be replaced.
- new − This is new substring, which would replace old substring.
- max − If this optional argument max is given, only the first count occurrences are replaced.
s1='I Love Python Tutorial, I Love ApkZube, I Love Coding'
print(s1.replace('Love','Like'))
print(s1.replace('I','He',2))
output of above example :
I Like Python Tutorial, I Like ApkZube, I Like Coding
He Love Python Tutorial, He Love ApkZube, I Love Coding
- split() - The split() method returns a list of all the words in the string, using str as the separator (splits on all whitespace if left unspecified), optionally limiting the number of splits to num.
str.split(str="", num = string.count(str)).
Example -
- str − This is any delimeter, by default it is space.
- num − this is number of lines to be made
s1='I Love Python,Java,Android,PHP,JavaScript'
print(s1.split(','))
print(s1.split(',',2)) #total 3 element in list
output of above example :
['I Love Python', 'Java', 'Android', 'PHP', 'JavaScript']
['I Love Python', 'Java', 'Android,PHP,JavaScript']
- swapcase() - The swapcase() method returns a copy of the string in which all the case-based characters have had their case swapped.
Example -
s1='I Love Python,Java,Android,PHP,JavaScript'
print(s1.swapcase())
output of above example :
i lOVE pYTHON,jAVA,aNDROID,php,jAVAsCRIPT